package com.zhangdi.mgsync.core.message;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author zhangdi
 * @version 1.0
 * @date 2023.6.16
 */
@Slf4j
@Component
public class EmailUtil {
    @Value("${alert_cfg.host}")
    String host;
    @Value("${alert_cfg.port}")
    String port;
    @Value("${alert_cfg.s_email}")
    String s_email;
    @Value("${alert_cfg.s_email_pwd}")
    String s_email_pwd;
    @Value("${alert_cfg.r_email}")
    String r_email;

    //是否处理 相同内容 某个时段内只发送一次处理
    public void send(String subject, String content) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                log.info("开始发送邮件通知");
                // 邮件发送配置
                Properties properties = new Properties();
                properties.put("mail.smtp.auth", "true");
                properties.put("mail.smtp.starttls.enable", "true");
                properties.put("mail.smtp.host", host);
                properties.put("mail.smtp.port", port);
                properties.put("mail.smtp.ssl.enable", true);

                Session session = Session.getInstance(properties, new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(s_email, s_email_pwd);
                    }
                });

                try {
                    // 创建邮件
                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(s_email));
                    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(r_email));
                    message.setSubject(subject);
                    message.setText(content);

                    // 发送邮件
                    Transport.send(message);
                    log.info("邮件发送完成");
                } catch (MessagingException e) {
                    log.error("邮件发送失败，t={},c={}", subject, content, e);
                }
            }
        });

        thread.start();
    }
}
